package niu.toy.spring.mvc;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;


/**
 * 记录 Action方法执行期间的相关数据
 */
@Data
public class ModelAndViewContainer {

    
    private Object view;
    
    private Map<String,Object> model;

    /**
     * http 状态码
     */
    
    private int status;

    /**
     是否处理完成
     */
    private boolean requestHandled = false;

    /**
     * 设置视图名称
     */
    public void setViewName( String viewName) {
        this.view = viewName;
    }
    public String getViewName() {
        return (this.view instanceof String ? (String) this.view : null);
    }

    /**
     *  若view是字符串则需要视图解析器 a ViewResolver.
     */
    public boolean isViewReference() {
        return (this.view instanceof String);
    }

    /**
     * 获取模型
     * @return
     */
    public Map<String, Object> getModel() {
        if (this.model == null) {
            this.model = new HashMap<>();
        }
        return this.model;
    }


    public ModelAndViewContainer addObject(String attributeName, Object attributeValue) {
        getModel().put(attributeName, attributeValue);
        return this;
    }

    public ModelAndViewContainer addAllObjects( Map<String, ?> modelMap) {
        getModel().putAll(modelMap);
        return this;
    }

    public ModelAndViewContainer removeObjects( Map<String, ?> attributes) {
        if (attributes != null) {
            for (String key : attributes.keySet()) {
                getModel().remove(key);
            }
        }
        return this;
    }

    /**
     * Return diagnostic information.
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("ModelAndViewContainer: ");
        if (isViewReference()) {
            sb.append("reference to view with name '").append(this.view).append("'");
        }
        else {
            sb.append("View is [").append(this.view).append(']');
        }
        sb.append(getModel());
        return sb.toString();
    }

}

